package com.uenpay.im.ui.old.activity.red;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.im.ui.old.activity.wallet.ChargeActivity;
import com.uenpay.im.ui.old.activity.wallet.WalletHandle;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.utilities.EditTextUtils;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.PayPwdDialog;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;

/**
 * @author SL
 * @created 2016-1-14 14:52:14
 * @copyRight http://www.qiyunxin.com
 * @function 发私聊红包
 */
public class SendRedToPersonalActivity extends BaseActivity {

    private Button send_btn;
    private EditText red_total_money_et, red_content_et;
    private TextView total_moeny_tv;
    private RedHandler mRedHendler = new RedHandler();
    private String cust_id, cust_name;
    private View loading;
    private double myBalance;
    private int haspaypassword;
    private TextView send_to_red;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_send_red_to_personal_layout;
    }

    @Override
    public void initView(View view) {
        cust_id = getIntent().getStringExtra("chat_id");
        cust_name = getIntent().getStringExtra("chat_name");
        initView();
        initListener();
        getMyBalance();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.send_red));
        total_moeny_tv = (TextView) findViewById(R.id.total_moeny_tv);
        red_total_money_et = (EditText) findViewById(R.id.red_total_money_et);
        red_content_et = (EditText) findViewById(R.id.red_content_et);
        send_btn = (Button) findViewById(R.id.send_btn);
        loading = findViewById(R.id.loading);
        send_to_red = (TextView) findViewById(R.id.send_to_red);
        send_to_red.setText(MessageFormat.format(
                getResources().getString(R.string.send_to_red), cust_name));
        int color = Color.argb(255, 0, 0, 0);
        ForegroundColorSpan normalSpan = new ForegroundColorSpan(color);
        SpannableStringBuilder builder = new SpannableStringBuilder(send_to_red
                .getText().toString());
        builder.setSpan(normalSpan, 4, send_to_red.getText().toString()
                .length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        send_to_red.setText(builder);
    }

    protected void initListener() {
        //返回键
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        red_total_money_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                if (!TextUtils.isEmpty(arg0)) {
                    checkRecharge();
                } else {
                    total_moeny_tv.setText("¥0.00");
                }
                checkBtnStatus();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        red_content_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                String content = red_content_et.getText().toString();
                if (Utils.String_length(content) > 50) {
                    if (content.length() > 25) {
                        red_content_et.setText(content.substring(0, 25));
                    }
                    return;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        send_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String content = getResources().getString(
                        R.string.red_default_content);
                String red_content = red_content_et.getText().toString();
                if (!TextUtils.isEmpty(red_content)) {
                    if (Utils.String_length(content) > 50) {
                        IMApplication.showToast(R.string.main_contacts);
                    } else {
                        content = red_content;
                    }
                }
                String total_money = red_total_money_et.getText().toString();
                if (!TextUtils.isEmpty(total_money)) {

                    double temp = Double.valueOf(total_money);
                    // if (temp > 10000) {
                    // showMoreDialog();
                    // } else {
                    if (temp > myBalance) {
                        showInsufficientBalanceDialog();
                    } else {
                        if (haspaypassword == 1) {
                            showPayPwdDialog(total_money, content);
                        } else {
                            showSetPwdDialog();
                        }
                    }
                    // }

                }
            }
        });
    }

//	private void showMoreDialog() {
//		DialogUtility.showSingleBtnDialog(SendRedToPersonalActivity.this,
//				R.string.crowdfund_max, R.string.comfirm, true,
//				new IOnBottomDialogListener() {
//
//					@Override
//					public void onClicked() {
//
//					}
//				});
//	}

    private void showSetPwdDialog() {
        DialogUtility.showDialog(SendRedToPersonalActivity.this,
                R.string.not_set_pay_pwd, R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(
                                SendRedToPersonalActivity.this,
                                SetPayPwdActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
    }

    /**
     * 支付密码提示框
     *
     * @param total_money
     * @param content
     */
    private void showPayPwdDialog(final String total_money, final String content) {
        PayPwdDialog.showBottomRedDialog(SendRedToPersonalActivity.this,
                new PayPwdDialog.IPayPwdInputFinishListener() {

                    @Override
                    public void onPayPwdInputFinish(String payPwd) {
                        createRed(total_money, content, payPwd);
                    }
                });
    }

    private void createRed(String amount, String content, String paypasswrod) {
        loading.setVisibility(View.VISIBLE);
        mRedHendler.createRed(amount, "1", 2, content, paypasswrod,
                new RedHandler.ICreateRedListener() {

                    @Override
                    public void onCreateRedResult(String packetsid, int status,
                                                  String msg) {
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            sendRed(packetsid);
                        } else if (status == 2505) {
                            // TODO 提示余额不足是否立即充值
                            loading.setVisibility(View.GONE);
                            showInsufficientBalanceDialog();
                        } else {
                            IMApplication.showToast(msg);
                            loading.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void sendRed(final String packetsid) {
        mRedHendler.sendRed(packetsid, cust_id, 1, new RedHandler.ISendRedResult() {

            @Override
            public void onSendResult(int status, String reason) {
                loading.setVisibility(View.GONE);
                if (status == HttpInvokeResultCode.RESULT_OK)
                    sendRedToTalk(packetsid);
                else if (status == 2505) {
                    // TODO 提示余额不足是否立即充值
                    showInsufficientBalanceDialog();
                } else {
                    IMApplication.showToast(reason);
                }
            }
        });
    }

    private void checkRecharge() {
        String money = red_total_money_et.getText().toString();
        if (!TextUtils.isEmpty(money)) {
            EditTextUtils.inputDecimal(red_total_money_et, red_total_money_et
                    .getText().toString());
            total_moeny_tv.setText("¥"
                    + red_total_money_et.getText().toString());
        }
    }

    private void checkBtnStatus() {
        String money = red_total_money_et.getText().toString();
        if (!TextUtils.isEmpty(money)) {
            send_btn.setEnabled(true);
            send_btn.setBackgroundResource(R.drawable.received_red_dialog_btn_selector);
        } else {
            send_btn.setEnabled(false);
            send_btn.setBackgroundResource(R.drawable.btn_open_red_shape_bg_uncheck);
        }
    }

    private void sendRedToTalk(String packetsid) {
        String content = getResources().getString(R.string.red_default_content);
        String red_content = red_content_et.getText().toString();
        if (!TextUtils.isEmpty(red_content)) {
            content = red_content;
        }
        Intent intent = new Intent();
        intent.putExtra("packetsid", packetsid);
        intent.putExtra("content", content);
        setResult(RESULT_OK, intent);
        Utils.hideSoftKeyboard(red_total_money_et);
        Utils.hideSoftKeyboard(red_content_et);
        sendBroadcast(new Intent("balance_change"));
        finish();
    }

    private void getMyBalance() {
        WalletHandle.getBalance(new WalletHandle.IGetBalanceResultListener() {

            @Override
            public void onGetBalanceResult(String balance, int status,
                                           int _haspaypassword) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    if (!TextUtils.isEmpty(balance)) {
                        myBalance = Double.valueOf(balance);
                    }
                    haspaypassword = _haspaypassword;
                }
            }
        });
    }

    private void showInsufficientBalanceDialog() {
        loading.setVisibility(View.GONE);
        DialogUtility.showDialog(SendRedToPersonalActivity.this,
                R.string.insufficient_balance, R.string.sure, R.string.cancel,
                true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(
                                SendRedToPersonalActivity.this,
                                ChargeActivity.class);
                        startActivityForResult(intent, 100);
                    }
                });
    }

}
